<?php
/**
 * Created by PhpStorm.
 * User: River
 * Email: river0428@gmail.com
 * Date: 2018/11/16
 * Time: 上午10:37
 */

namespace Modules\Admin\Main\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Page;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class PageController extends Controller
{
    public function index()
    {
        return view('main::page', \Request::all());
    }

    public function all()
    {
        $data['items'] = Page::orderBy('id', 'desc')->get();
        return success($data);
    }

    public function show($id)
    {
        $data = Page::find($id);

        return success($data);
    }

    public function store(Request $request)
    {
        $data = $request->only(['name', 'title', 'content']);
        $validator = Validator::make($request->all(), [
            'name' => 'required|unique:page',
            'title' => 'required',
            'content' => 'required'
        ]);
        if ($validator->fails()) {
            return fail(400, $validator->errors()->first());
        }
        Page::create($data);
        return success();
    }

    public function update(Request $request, $id)
    {
        $page = Page::find($id);
        $title = $request->input('title');
        $content = $request->input('content');
        if ($title) {
            $page->title = $title;
        }
        if ($content) {
            $page->content = $content;
        }
        $page->save();
        return success();
    }
}